﻿/*******************************************************************************
 * Copyright © 2020 QuartzUI.Framework 版权所有
 * Author: QuartzUI
 * Description: QuartzUI快速开发平台
 * Website：
*********************************************************************************/

using System;
using Microsoft.AspNetCore.Mvc;
using QuartzUI.Service;
using QuartzUI.Service.SystemSecurity;
using QuartzUI.Code;
using QuartzUI.Domain.SystemSecurity;
using System.Threading.Tasks;
using QuartzUI.Service.SystemOrganize;
using QuartzUI.Domain.SystemOrganize;
using SqlSugar;
using System.Linq;
using System.Text;

namespace QuartzUI.Web.Controllers
{
	public class LoginController : Controller
    {
        public UserService _userService { get; set; }
        public ISqlSugarClient _context { get; set; }
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.SqlMode = "";
            ViewBag.ProjectName = "Quartz UI";
            ViewBag.LogoIcon = "../icon/favicon.ico";
            return View();
        }
        /// <summary>
        /// 验证码获取（此接口已弃用）
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetAuthCode()
        {
            return File(new VerifyCodeHelper().GetVerifyCode(), @"image/Gif");
        }
        [HttpGet]
        public async Task<ActionResult> OutLogin()
        {
            await OperatorProvider.Provider.EmptyCurrent("pc_");
            return Content(new AlwaysResult { state = ResultType.success.ToString() }.ToJson());
        }
        /// <summary>
        /// 验证登录状态请求接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [IgnoreAntiforgeryToken]
        public async Task<ActionResult> CheckLoginState()
        {
            try
            {
                //登录检测      
                if ((await OperatorProvider.Provider.IsOnLine("pc_")).stateCode<=0)
                {
                    await OperatorProvider.Provider.EmptyCurrent("pc_");
                    return Content(new AlwaysResult { state = ResultType.error.ToString() }.ToJson());
                }
                else
                {
                    return Content(new AlwaysResult { state = ResultType.success.ToString() }.ToJson());
                }
            }
            catch (Exception)
            {
                return Content(new AlwaysResult { state = ResultType.error.ToString() }.ToJson());
            }

        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="username">用户</param>
        /// <param name="password">密码</param>
        /// <param name="localurl">域名</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [IgnoreAntiforgeryToken]
        public async Task<ActionResult> CheckLogin(string username, string password)
        {
            try
            {
                UserEntity userEntity =await _userService.CheckLogin(username, password);
                OperatorModel operatorModel = new OperatorModel();
                operatorModel.UserId = userEntity.Id;
                operatorModel.UserCode = userEntity.Account;
                operatorModel.UserName = userEntity.RealName;
                operatorModel.CompanyId = userEntity.OrganizeId;
                operatorModel.DepartmentId = userEntity.DepartmentId;
                operatorModel.RoleId = userEntity.RoleId;
                operatorModel.LoginIPAddress = WebHelper.Ip;
                if (GlobalContext.SystemConfig.LocalLAN != false)
                {
                    operatorModel.LoginIPAddressName = "本地局域网";
                }
                else
                {
                    operatorModel.LoginIPAddressName = WebHelper.GetIpLocation(operatorModel.LoginIPAddress);
                }
                operatorModel.LoginTime = DateTime.Now;
                operatorModel.DdUserId = userEntity.DingTalkUserId;
                operatorModel.WxOpenId = userEntity.WxOpenId;
                //各租户的管理员也是当前数据库的全部权限
                operatorModel.IsSuperAdmin = userEntity.IsAdmin.Value;
                operatorModel.IsAdmin = userEntity.IsAdmin.Value;
                operatorModel.IsBoss = userEntity.IsBoss.Value;
                operatorModel.IsLeaderInDepts = userEntity.IsLeaderInDepts.Value;
                operatorModel.IsSenior = userEntity.IsSenior.Value;
                operatorModel.DbNumber = GlobalContext.SystemConfig.MainDbNumber;
                if (operatorModel.IsAdmin && operatorModel.DbNumber == GlobalContext.SystemConfig.MainDbNumber)
                {
                    operatorModel.IsSuperAdmin = true;
                }
                else
                {
                    operatorModel.IsSuperAdmin = false;
                }
                //缓存保存用户信息
                await OperatorProvider.Provider.AddLoginUser(operatorModel, "","pc_");
                //防重复token
                string token = Utils.GuId();
                HttpContext.Response.Cookies.Append("pc_" + GlobalContext.SystemConfig.TokenName, token);
                await CacheHelper.SetAsync("pc_" + GlobalContext.SystemConfig.TokenName + "_" + operatorModel.UserId + "_" + operatorModel.LoginTime, token, GlobalContext.SystemConfig.LoginExpire, true);
                return Content(new AlwaysResult { state = ResultType.success.ToString(), message = "登录成功。"}.ToJson());
            }
            catch (Exception ex)
            {
                return Content(new AlwaysResult { state = ResultType.error.ToString(), message = ex.Message }.ToJson());
            }
        }
    }
}
